package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;;
import java.util.Map;
/*
 * 手机号快速登录
 * */

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    private Result login(HttpServletResponse response, @RequestBody Map map) {
        //得到页面的验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //得到redis服务器的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        if (validateCode != null && codeInRedis != null && validateCode.equals(codeInRedis)) {
            //验证成功
            //判断是不是会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                // 会员直接登录 不是会员则自动注册
                member = new Member();
                member.setPhoneNumber((String) map.get("phoneNumber"));
                memberService.add(member);
            }
            //  TODO将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟这是？、？？

            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");//路径
            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);

        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
